<template>
    <div class="mail-chat">
        <CheckItem :show.sync="checkItemModal" :data="checkItem" @save="saveCheckItem" model="Order"
                   :itemID="itemID"></CheckItem>
        <ItemDetail :loading="tableLoading" :show.sync="showModal" :value="item" title="Edit Item" :id="itemID"
                    @submit="confirmSubmit"
                    action="edit" :height="600" :arrow="questionnaires.length > 1" @arrow="changeItem"
                    :arrowCanPrevious="arrowCanPrevious" :arrowCanNext="arrowCanNext"
        ></ItemDetail>
        <modal id="chat-calendar" :show.sync="showCalendarModal" :dialogCSS="{'width': '70%'}">
            <template slot="header">
                {{ related && related.room.length ? related.room[relatedRoomIndex].physical_room_id : ''}}
            </template>
            <template slot="body">
                <full-calendar value="airbnb" :events="events" :priceData="priceData"></full-calendar>
            </template>
            <template slot="footer">
                <div></div>
            </template>
        </modal>
        <modal :show.sync="showHtmlModal" id="html-modal" :dialogCSS="{'width': '70%'}">
            <template slot="header" v-if="currentMsg">
                {{currentMsg.subject}}
            </template>
            <template slot="body">
                <div style="height: 600px;" id="iframe-wrapper"></div>
            </template>
            <template slot="footer">
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
            </template>
        </modal>
        <modal :show.sync="showIssuesModal" id="issues-modal">
            <template slot="header"></template>
            <template slot="body">
                <div>
                    <div class="form-group">
                        <label for="">Category</label>
                        <select class="form-control" v-model="issue.type">
                            <option :key="'tag' + index" v-for="(tag, index) in $store.state.issuesType" :value="tag">
                                {{tag}}
                            </option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="">Type Code
                            <i v-tooltip.top="`Get Issue Tip`" class="fif fif-tip text-info" style="cursor: pointer;"
                               @click="getIssueTip"></i>
                        </label>
                        <menu-select :init="showIssuesModal" v-model="issue.type_code"></menu-select>
                    </div>
                    <div class="form-group">
                        <label for="">Title <i class="text-danger">*</i></label>
                        <input v-model="issue.summary" type="text" class="form-control" placeholder="Title"></div>
                    <div class="form-group">
                        <label for="">Content <i class="text-danger">*</i></label>
                        <textarea rows="10" v-model="issue.message" class="form-control"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="">Related Message</label>
                        <textarea rows="4" v-model="issueRelatedMessage" class="form-control"></textarea>
                    </div>
                </div>
            </template>
            <template slot="footer">
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-danger waves-effect waves-light" @click="addIssue">Submit</button>
            </template>
        </modal>
        <modal :show.sync="showTemplateModal" id="template-modal" :dialogCSS="{'width': '70%'}">
            <template slot="header">
                Reply Template
            </template>
            <template slot="body">
                <div>
                    <!-- Nav tabs -->
                    <ul class="nav customtab nav-tabs" role="tablist">
                        <li role="presentation" class="active" @click="changeTemplate('zh')">
                            <a href="#china" aria-controls="home" role="tab" data-toggle="tab" aria-expanded="true">
                                <!--<span class="visible-xs"><i class="ti-home"></i></span>-->
                                <span class="hidden-xs"> Chinese</span>
                            </a>
                        </li>
                        <li role="presentation">
                            <a href="#english" aria-controls="home" @click="changeTemplate('en')" role="tab"
                               data-toggle="tab" aria-expanded="true">
                                <span class="hidden-xs"> English</span>
                            </a>
                        </li>
                        <li role="presentation">
                            <a href="#japan" @click="changeTemplate('jp')" aria-controls="home" role="tab"
                               data-toggle="tab" aria-expanded="true">
                                <span class="hidden-xs"> Japanese</span>
                            </a>
                        </li>
                    </ul>
                    <!-- Tab panes -->
                    <div class="tab-content m-t-10">
                        <div role="tabpanel" class="tab-pane fade active in" id="china">
                            <span class="text-danger" style="font-size: 12px;">* Enter words that needs to be replaced by surround them with {}</span>
                            <tree v-if="templateData.zh" id="zh-reply-tree" :data="templateData.zh"
                                  @cancelModal="showTemplateModal = false"
                                  @showModal="showTemplateModal = true"
                                  @selected="getCurrentNode"
                                  @create="createTemplate"
                                  @delete="deleteTemplate"
                                  @update="updateTemplate"
                            >
                            </tree>
                        </div>
                        <div role="tabpanel" class="tab-pane fade" id="english">
                            <tree v-if="templateData.en" id="en-reply-tree" :data="templateData.en"
                                  @cancelModal="showTemplateModal = false"
                                  @showModal="showTemplateModal = true"
                                  @selected="getCurrentNode"
                                  @create="createTemplate"
                                  @delete="deleteTemplate"
                                  @update="updateTemplate"
                            >
                            </tree>
                        </div>
                        <div role="tabpanel" class="tab-pane fade" id="japan">
                            <tree v-if="templateData.jp" id="jp-reply-tree" :data="templateData.jp"
                                  @cancelModal="showTemplateModal = false"
                                  @showModal="showTemplateModal = true"
                                  @selected="getCurrentNode"
                                  @create="createTemplate"
                                  @delete="deleteTemplate"
                                  @update="updateTemplate"
                            >
                            </tree>
                        </div>
                    </div>
                </div>
            </template>
            <template slot="footer">
                <button type="button" class="btn btn-success waves-effect" @click="selectTemplate">Select</button>
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
            </template>
        </modal>
        <div class="chat-main-box">
            <div class="chat-toggle-wrapper">
                <div class="chat-btn" @click="reloadChat" :class="{'active': currentChatView === 'NEW'}">
                    <i class="fif fif-message"></i>
                </div>
                <div class="chat-btn" @click="loadBookmarkedChat" :class="{'active': currentChatView === 'BOOKMARK'}">
                    <i class="fif fif-star"></i>
                </div>
            </div>
            <!-- .chat-left-panel -->
            <div class="chat-left-aside">
                <div class="open-panel" @click="openChatList()"><i class="fif fif-cc-arrow-right"></i></div>
                <div class="chat-left-inner">
                    <div class="chat-left-header">
                        <span class="text">Guest</span>
                        <div class="chat-lang-wrapper clearfix">
                            <ul class="nav chat-lang">
                                <li class="lang">
                                    <ChatLangCtl tag="all" v-model="keyChatLang"></ChatLangCtl>
                                </li>
                                <li class="lang">
                                    <ChatLangCtl tag="en" v-model="keyChatLang"></ChatLangCtl>
                                </li>
                                <li class="lang">
                                    <ChatLangCtl tag="zh" v-model="keyChatLang"></ChatLangCtl>
                                </li>
                                <li class="lang">
                                    <ChatLangCtl tag="ja" v-model="keyChatLang"></ChatLangCtl>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="form-material">
                        <div class="input-group">
                            <input class="form-control p-20" type="text" placeholder="Search Contact"
                                   v-model="searchKeyword" @keydown.enter.stop="search">
                            <span class="input-group-btn" @click="search">
                                <button class="btn btn-info" type="button" :disabled="currentChatView === 'BOOKMARK'"><i
                                        class="fif fif-search"></i></button>
                            </span>
                        </div>
                    </div>
                    <ul class="nav nav-tabs" role="tablist" v-show="currentChatView !== 'BOOKMARK'">
                        <li role="presentation" class="active text-center" style="width: 50%;">
                            <a href="javascript:void(0)" @click="loadChat('new')" aria-controls="new" role="tab"
                               data-toggle="tab" aria-expanded="true">
                                <span class="hidden-xs"> New</span>
                            </a>
                        </li>
                        <li role="presentation" style="width: 50%" class="text-center">
                            <a href="javascript:void(0)" @click="loadChat('replied')" aria-controls="profile" role="tab"
                               data-toggle="tab" aria-expanded="false">
                                <span class="hidden-xs"> Replied</span>
                            </a>
                        </li>
                    </ul>
                    <ul class="chatonline style-none" v-if="chatList"
                        style="position: relative;min-height:100px;overflow: visible;">
                        <Loading :show="loading"></Loading>
                        <li :key="'chat' + index" v-for="(chat, index) in chatList.chat_list"
                            :class="{'active': currentChat && currentChat.chat_id === chat.chat_id}"
                            :style="{backgroundColor: currentChat && currentChat.chat_id === chat.chat_id ? activeChatColor : ''}"
                            @click="showMessage(chat)" class="clearfix"
                        >
                            <a href="javascript:void(0)" :class="{'unseen': chat.is_new && parseInt(chat.unseen_num)}"
                               style="display: flex;position: relative;">
                                <div style="flex: 1">
                                    <i style="font-family: Arial; width: 18px; height: 18px; line-height: 18px; border-radius: 30%; display: inline-block;
                                      background: red; margin-bottom: 4px; color: #fff;text-align: center;font-size: 12px;"
                                       v-if="chat.is_new && parseInt(chat.unseen_num)">
                                        {{ parseInt(chat.unseen_num) > 9 ? '9+' : chat.unseen_num }}
                                    </i>
                                    <span class="name" style="word-break: break-all">
                                        {{chat.name}}
                                        <small class="text-success">{{`${chat.platform}(${chat.chat_id})`}}</small>
                                    </span>
                                </div>
                                <div>
                                    <div class="label time pull-right"
                                         style="color: grey;">
                                        {{ formatTime(chat.latest_date) }}
                                        <i v-if="type === 'new'" class="fif fif-cc-arrow-right text-warning"
                                           v-tooltip.top="'mark as replied'" @click.stop="mark(chat.chat_id, 'replied')"
                                           style="cursor: pointer"></i>
                                        <i v-if="type === 'replied'" class="fif fif-cc-arrow-left text-warning"
                                           v-tooltip.top="'mark as new'" @click.stop="mark(chat.chat_id, 'new')"
                                           style="cursor: pointer"></i>
                                    </div>
                                </div>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            <!-- .chat-left-panel -->
            <!-- .chat-right-panel -->
            <div class="chat-right-aside">
                <div class="chat-main-header">
                    <div class="p-10 b-b">
                        <h3 class="box-title clearfix">
                            <span style="font-size: 14px;" v-if="currOrder">
                              <strong style="font-size: 18px;">{{currOrder.guest_name}}</strong>
                              <strong style="color: #818181;">{{currOrder.guest_num}}位房客</strong>
                               <strong style="font-size: 16px;">	&bull;</strong>
                              <strong style="color: #818181;">{{currOrder.days}}晚</strong>
                               <strong style="font-size: 16px;">	&bull;</strong>
                              <strong style="color: #818181;">{{currOrder.total_cost}}{{currOrder.currency}}</strong>
                            </span>
                            <span style="font-size: 14px;" v-if="currentChat">{{currentChat.addr}}</span>
                            <span style="font-size: 14px;"
                                  v-if="currentChat && currentChat.origin_to_addr && currentChat.is_bookmarked">{{`(${currentChat.origin_to_addr})`}}</span>

                            <div class="pull-right">
                                <div v-if="currentChat" class="chat-lang-ctl dropdown"
                                     style="display: inline-block;vertical-align: middle;">
                                    <a class="country-wrapper" data-toggle="dropdown">
                                        <img v-show="chatLang === 'en'" src="@/static/img/england.png" alt=""
                                             class="country">
                                        <img v-show="chatLang === 'zh-cn'" src="@/static/img/china.png" alt=""
                                             class="country">
                                        <img v-show="chatLang === 'ja'" src="@/static/img/japan.png" alt=""
                                             class="country">
                                        <img v-show="chatLang === 'NA'" src="@/static/img/speical.png" alt=""
                                             class="country">
                                    </a>
                                    <ul class="dropdown-menu animated fadeIn pull-right"
                                        @click.stop="chatLangFlag = true" style="padding: 0 10px;">
                                        <li class="lang-ctl">
                                            <radio name="lang" value="en" v-model="chatLang">en</radio>
                                        </li>
                                        <li class="lang-ctl">
                                            <radio name="lang" value="zh-cn" v-model="chatLang">zh</radio>
                                        </li>
                                        <li class="lang-ctl">
                                            <radio name="lang" value="ja" v-model="chatLang">jp</radio>
                                        </li>
                                        <li class="lang-ctl">
                                            <radio name="lang" value="NA" v-model="chatLang">NA</radio>
                                        </li>
                                    </ul>
                                </div>
                                <i v-if="currentChat && currentChat.is_bookmarked" class="bookmark fif fif-star"
                                   @click="toggleBookmark(false)"></i>
                                <i v-else-if="currentChat" class="bookmark fif fif-star-border"
                                   @click="toggleBookmark(true)"></i>
                            </div>


                        </h3>

                      <!--
                        <div v-if="msgList && msgList.chat_info">
                            <small :key="'tag' + index" class="label"
                                   style="cursor: pointer;margin-right: 5px;display: inline-block;background: #d9edf7"
                                   v-for="(tag, index) in tags"
                                   :class="genTagClass(msgList, tag)"
                                   @click="setLabel(msgList.chat_info, tag.value)"
                            >{{tag.label}}
                            </small>
                        </div>
                         -->
                    </div>
                </div>
                <div class="chat-box">
                    <Loading :show="loadingMessage"></Loading>
                    <ul class="chat-list slimscroll p-t-30">
                        <li style="overflow: hidden;" :key="'msg' + index" v-for="(msg, index) in msgList.msg_list"
                            :class="{'odd': msg.send_from_funkey}" :id="msg.msg_id">
                            <div class="chat-image">
                                <img v-if="msg.send_from_funkey" alt="avatar" src="@/static/img/funkey-avatar.png">
                                <img v-else-if="msgList.chat_info.platform.toLowerCase().indexOf('airbnb') != -1"
                                     alt="avatar" src="@/static/img/airbnb.jpg">
                                <img v-else-if="msgList.chat_info.platform.toLowerCase().indexOf('tujia') != -1"
                                     alt="avatar" src="@/static/img/tujia.png">
                                <img v-else-if="msgList.chat_info.platform.toLowerCase().indexOf('asiayo') != -1"
                                     alt="avatar" src="@/static/img/asiayo.jpg">
                                <img v-else-if="msgList.chat_info.platform.toLowerCase().indexOf('agoda') != -1"
                                     alt="avatar" src="@/static/img/agoda.jpg">
                                <img v-else-if="msgList.chat_info.platform.toLowerCase().indexOf('zizaike') != -1 || msgList.chat_info.platform.toLowerCase().indexOf('booking') != -1"
                                     alt="avatar" src="@/static/img/zizaike.jpg">
                                <img v-else="" alt="avatar" src="@/static/img/unkonwn.png"/>
                            </div>
                            <div class="chat-body">
                                <div class="chat-text" style="text-align: left;max-width: 120%; word-wrap:break-word;"
                                     :class="String(msg.template_type).indexOf(':confirm') !== -1 ? 'bg-success text-white': String(msg.template_type).indexOf(':inquiry') !== -1 ? 'bg-warning text-white' : ''">
                                    <div>{{msg.subject}}</div>
                                    <div :key="'line' + index" v-for="(line, index) in formatText(msg.plain)"
                                         style="font-weight: 700">
                                        {{ line }}
                                    </div>
                                    <div class="translate-wrapper" v-if="msg.translated" v-text="msg.translated">
                                    </div>

                                    <div style="vertical-align: middle;">
                                        <b>{{formatTime(msg.date)}}</b>
                                        <i class="fif fif-html text-info" v-tooltip.top="'Show HTML'"
                                           style="cursor: pointer; font-size: 20px;"
                                           @click="toShowHtml(msg)" data-toggle="tooltip"></i>
                                        <i class="fif fif-add-text text-primary"
                                           style="cursor: pointer; font-size: 20px;" v-tooltip.top="'Add Issue'"
                                           @click="toShowIssue(msg)"></i>
                                        <i class="fif fif-Translate text-warning"
                                           style="cursor: pointer; font-size: 20px;" v-tooltip.top="'Translate'"
                                           @click="toTranslate(msg)"></i>
                                        <span class="label label-success pull-right m-t-15" v-if="msg.sender_user_name">
                                        {{msg.sender_user_name}}
                                    </span>
                                    </div>

                                </div>
                            </div>
                        </li>
                    </ul>
                    <div class="row send-chat-box bg">
                        <div class="col-sm-12"
                             style="padding-left: 30px;overflow: hidden;display: flex; padding-bottom: 4px;">
                            <div>
                                <MenuSelectTemplate wrapper="ctl-menu-template-zh" content="ctl-menu-content-zh"
                                                    @input="selectTemplateFromMenu"
                                                    :categories="templateDataTree['zh']">
                                    <template slot="target">
                                        <img src="../../static/img/china.png" alt="" width="30"
                                             style="display: inline-block;cursor: pointer;border:1px solid #ddd;"
                                             class="ctl-menu-template-zh">
                                    </template>
                                </MenuSelectTemplate>
                            </div>

                            <div style="margin-left: 10px;">
                                <MenuSelectTemplate wrapper="ctl-menu-template-jp" content="ctl-menu-content-jp"
                                                    @input="selectTemplateFromMenu"
                                                    :categories="templateDataTree['jp']">
                                    <template slot="target">
                                        <img src="../../static/img/japan.png" alt="" width="30"
                                             style="display: inline-block;cursor: pointer;border:1px solid #ddd;"
                                             class="ctl-menu-template-jp">
                                    </template>
                                </MenuSelectTemplate>
                            </div>

                            <div style="margin-left: 10px;">
                                <MenuSelectTemplate wrapper="ctl-menu-template-en" content="ctl-menu-content-en"
                                                    @input="selectTemplateFromMenu"
                                                    :categories="templateDataTree['en']">
                                    <template slot="target">
                                        <img src="../../static/img/england.png" alt="" width="30"
                                             style="display: inline-block;cursor: pointer;border:1px solid #ddd;"
                                             class="ctl-menu-template-en">
                                    </template>
                                </MenuSelectTemplate>
                            </div>

                            <div style="margin-left: 10px;"
                                 v-show="related && related.room.length && specialTreeData.length && specialTreeData[0].children">
                                <MenuSelectTemplate wrapper="ctl-menu-template-spec" content="ctl-menu-content-spec"
                                                    @input="selectTemplateFromMenu" :categories="specialTreeData">
                                    <template slot="target">
                                        <img src="../../static/img/speical.png" alt="" width="30"
                                             style="display: inline-block;cursor: pointer;border:1px solid #ddd;"
                                             class="ctl-menu-template-spec">
                                    </template>
                                </MenuSelectTemplate>
                            </div>
                        </div>
                        <div class="col-sm-12">
                            <textarea class="form-control" placeholder="Type your message"
                                      v-model="message.content"></textarea>
                            <div class="clearfix">
                                <ul class="nav pull-left p-l-10 p-r-10">
                                    <li :key="'template' + index" v-for="(template, index) in hotTemplates"
                                        v-tooltip.top="template" class="hot-template m-r-5 m-b-5"
                                        @click="clickTemplate(template)">
                                        <span class="label"
                                              :class="['label-primary', 'label-info', 'label-warning', 'label-success', 'label-danger'][index % 5]">
                                            {{template}}
                                        </span>
                                    </li>
                                </ul>
                                <div class="pull-right m-r-20 m-b-10">
                                    <div class="dropdown dropup" style="display: inline-block;">
                                        <a data-toggle="dropdown" href="#" v-tooltip.top="'Translate'" class="dropdown-toggle cst-icon m-r-10"
                                        ><i class="fif fif-Translate" style="font-size: 20px;"></i></a>
                                        <div class="dropdown-menu pull-right p-10">
                                            <form class="form-horizontal form-bordered">
                                                <div class="form-body">
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <label class="control-label col-md-3">Source</label>
                                                        <div class="col-md-12">
                                                            <select class="form-control" v-model="sourceLang">
                                                                <option value="zh-cn">zh-cn</option>
                                                                <option value="en">en</option>
                                                                <option value="ja">ja</option>
                                                                <option value="th">th</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="form-group" style="margin-bottom: 10px;">
                                                        <label class="control-label col-md-3">Target</label>
                                                        <div class="col-md-12">
                                                            <select class="form-control"  v-model="targetLang">
                                                                <option value="zh-cn">zh-cn</option>
                                                                <option value="en">en</option>
                                                                <option value="ja">ja</option>
                                                                <option value="th">th</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="form-actions" style="text-align: right;">
                                                        <button type="button" class="btn btn-xs btn-success" @click="translateMessage">Submit</button>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                    <a href="javascript:void(0)" v-tooltip.top="'Template'" class="cst-icon m-r-10"
                                       @click="showTemplate"
                                    ><i class="fif fif-template" style="font-size: 20px;"></i></a>
                                    <a href="javascript:void(0)" class="cst-icon m-r-10"
                                       v-tooltip.top="'attachment'"
                                       @click="showFileWindow()">
                                        <input @change="getFile($event)" multiple="multiple" type="file" class="hidden"
                                               id="chat-file"/>
                                        <i class="fif fif-attach" style="font-size: 16px;"></i></a>
                                    <button class="btn btn-danger btn-rounded" type="button" @click="sendMessage">Send
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- .chat-right-panel -->
            <div class="chat-aside" style="overflow-y: auto;">
                <div class="chat-aside-content" v-if="related && related.room.length">
                    <h2 class="pid-title">
                        PID:
                        <select name="" id="" v-if="related.room.length > 1" v-model="relatedRoomIndex" @change="_resetRelated">
                            <option v-for="(room, index) in related.room" :value="index">{{room.physical_room_id}}</option>
                        </select>
                        <span v-else>{{related.room[0].physical_room_id}}</span>
                        <span class="text-primary pull-right" v-if="related && related.order && related.order.length">{{related.order[0].reservation_code}}</span>
                    </h2>
                    <v-gallery type="carousel" v-if="related.room[relatedRoomIndex].room_photos"
                               :images="related.room[relatedRoomIndex].room_photos"></v-gallery>
                    <img class="room-img" v-else src="../../static/img/img1.jpg" alt=""/>
                    <div class="room-title-wrapper">
                        <div class="room-title-left">
                            <a v-if="msgDetail.link" :href="msgDetail.link" target="_blank" class="room-title"
                               style="text-decoration: underline;">
                                {{msgDetail.title}}
                            </a>
                            <h3 v-else class="room-title" style="min-height: 20px;">
                                {{msgDetail.title}}
                            </h3>

                            <p class="room-location">
                                <a target="_blank"
                                   :href="'https://www.google.com/maps/search/?api=1&query=' + related.room[relatedRoomIndex].location">Location:
                                    {{related.room[relatedRoomIndex].location}}</a>
                            </p>
                        </div>
                        <div class="room-title-right">
                            <img v-if="this.msgDetail.userImg" :src="msgDetail.userImg" alt="">
                            <img v-else src="../../static/img/unkonwn.png" alt="">
                        </div>
                    </div>

                  <div class="info-wrapper" v-if="showButtons">
                    <div v-if="currReservation.status == 'reservation_pending'">
                      <el-button style="background-color: #1E88E5;color: white; width: 100%;" round @click="doAccept" :loading="submitLoading">接受</el-button>
                      <el-button style="width: 100%;margin:10px 5px 0px 0px;" round :disabled="!(currReservation.status == 'reservation_pending')"  @click="doRefuse" :loading="submitLoading">拒绝</el-button>
                    </div>
                    <div v-else>
                      <!-- 预准按钮 -->
                      <el-button style="background-color: #1E88E5;color: white; width: 100%;" round  @click="doApproval" :loading="submitLoading">{{preApprovalBtnTxt}}</el-button>
                      <!--
                       可以拒绝订单的情况下，chat_related_info接口返回的值里面一定有reservation。
                      只有当reservation的status为reservation_pending时，才可以拒绝。
                      否则按钮是不能按的。当status为reservation_declined时，表示订单已经被拒绝，按钮也不能按。
                      -->
                      <el-button style="width: 46%;margin-top:10px;" round :disabled="!(currReservation.status == 'reservation_pending')" @click="doRefuse" :loading="submitLoading">拒绝</el-button>
                      <!-- 特别优惠按钮 -->
                      <el-button  style="width: 46%;margin-top:10px;" round @click="doSpecial" :loading="submitLoading">{{favourableBtnTxt}}</el-button>
                    </div>
                  </div>
                    <div class="info-wrapper">
                        <div class="info-top">
                            <div class="info-item">
                                <p class="key">STATUS</p>
                                <div class="val">
                                    {{related && related.order &&related.order.length ? related.order[0].status : ''}}
                                </div>
                            </div>
                            <div class="info-item">
                                <p class="key">PLATFORM</p>
                                <div class="val">
                                    {{related && related.order.length ? related.order[0].platform : ''}}
                                </div>
                            </div>
                            <div class="btn-wrapper">
                                <i class="fif fif-calendar text-info"
                                   style="font-size: 20px;margin-right: 5px;cursor: pointer;"
                                   @click="toShowCalendarModal"
                                ></i>
                                <button type="button" class="btn btn-primary  btn-circle btn-sm m-r-5"
                                        v-tooltip.top="'CheckList'"
                                        @click="_checkList"
                                >
                                    <i class="fif fif-check_list-border"></i>
                                </button>
                                <button type="button" class="btn btn-warning  btn-circle btn-sm m-r-5"
                                        v-tooltip.top="'Order'"
                                        @click="toShowOrder"
                                >
                                    <i class="fif fif-cny"></i>
                                </button>
                                <button type="button" class="btn btn-info btn-circle btn-sm m-r-5"
                                        v-tooltip.top="'PhysicalRoom'"
                                        @click="toShowRoom"
                                >
                                    <i class="fif fif-home"></i>
                                </button>
                                <button type="button" class="btn btn-danger btn-circle btn-sm m-r-5"
                                        v-tooltip.top="'Questionnaire'"
                                        @click="toShowQuestionnaire"
                                >
                                    <i class="fif fif-other-list"></i>
                                </button>
                            </div>
                        </div>
                        <div class="info-bottom">
                            <div class="info-item">
                                <p class="key">CHECK IN</p>
                                <div class="val">
                                    {{related && related.order.length ? related.order[0].checkin : ''}}
                                </div>
                                <div class="check-time">
                                    {{related && related.order.length ? related.order[0].checkin_time : ''}}
                                </div>
                            </div>
                            <div class="info-item">
                                <p class="key">CHECK OUT</p>
                                <div class="val">
                                    {{related && related.order.length ? related.order[0].checkout : ''}}
                                </div>
                                <div class="check-time">
                                    {{related && related.order.length ? related.order[0].checkout_time : ''}}
                                </div>
                            </div>
                            <div class="info-item">
                                <p class="key">NIGHTS</p>
                                <div class="val">
                                    {{related && related.order.length ? _getNights(related.order[0]) : ''}}
                                </div>
                            </div>
                            <div class="info-item">
                                <p class="key">GUEST</p>
                                <div class="val">
                                    {{related && related.order.length ? related.order[0].guest_num : ''}}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="note order-note-wrapper"
                         style="margin-top: 6px; border-bottom :1px solid #f2f3f4;padding-bottom: 10px;">
                        <div class="note-top" style="padding: 4px;background-color: #427ab2;color: #fff;">
                            Order Note
                        </div>
                        <div style="padding: 4px;display: flex;font-weight: bold;">
                            <div>
                                <div>
                                    <span>Cleaner: </span>
                                    <span>
                                          {{related && related.room.length ? related.room[0].cleaner : ''}}
                                    </span>
                                </div>
                                <div>
                                    <span>Price Reference: </span>
                                    <span>
                                          {{related && related.room.length ? related.room[0].ical_value : ''}}
                                    </span>
                                </div>
                            </div>
                            <div style="flex: 1;margin-left: 10px;text-align: right;">
                                {{related && related.order.length ? related.order[0].comment : ''}}

                            </div>
                        </div>
                    </div>
                    <div style="margin-top: 6px; border-bottom :1px solid #f2f3f4;">
                        <div class="note-top" style="padding: 4px;background-color: #427ab2;color: #fff;">
                            Room Note
                        </div>
                        <div style="padding: 4px; color: #000;font-weight: bold;">
                            <ul v-if="related && related.comment">
                                <li :key="'comment' + index"
                                    v-for="(comment, index) in _getComments(related.comment).split('\r\n')"
                                    v-if="comment.trim().length">
                                    {{comment}}
                                </li>
                            </ul>
                            <ul v-else></ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
      <!--******* 2020.03.03 外包加入  CODE START *******-->
      <el-dialog title="拒绝原因" :visible.sync="refuseFormVisible">
        <el-form ref="refuseForm" :model="refuseForm" :rules="refuseRule"  label-position="top"  v-loading="refuseFormLoading">
          <el-row>
            <el-col :span="24" style="font-size:16px;font-weight: bold;margin-bottom: 10px;">
              1.为什么您拒绝这个预约申请？（以下为四个选项框，单选）
            </el-col>
          </el-row>
          <el-form-item prop="decline_category">
            <el-radio-group v-model="refuseForm.decline_category">

              <el-row>
                <el-col :span="24">
                  <el-radio label="dates_not_available">预定申请的日期不再可用</el-radio>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-radio label="not_a_good_fit">我的房间不满足客人的要求</el-radio>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-radio label="waiting_for_better_reservation">我对于本预定的时间和价格或者入住日期有别的需求</el-radio>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-radio label="not_comfortable">我对这个预定感觉到不舒服</el-radio>
                </el-col>
              </el-row>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-col :span="24" style="font-size:16px;font-weight: bold;margin-bottom: 10px;">
              2.告诉客人，为什么我们不能够接受这个订单?
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" >
              <el-form-item label="2.1) 拒绝原因（公开）" prop="decline_reason_public">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 8}"
                  placeholder="请输入拒绝原因（公开）"
                  v-model="refuseForm.decline_reason_public">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" >
              <el-form-item label="2.2) 拒绝原因（非公开）" prop="decline_reason_private">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 8}"
                  placeholder="请输入拒绝原因（非公开）"
                  v-model="refuseForm.decline_reason_private">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item style="text-align: center;">
            <el-button type="primary" @click="doSubmitRefuse">提交</el-button>
            <el-button @click="doCloseRefuse">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!--******  发送预准/发送特殊优惠 ****-->
      <el-dialog :title="'Send A Special Offer 【'+actionTitle+'】'" :visible.sync="specialFormVisible" width="38%">
        <el-form ref="specialForm" :model="specialForm" :rules="specialRule"  label-position="top" :disabled="isBack"  v-loading="specialFormLoading">
          <el-row>
            <el-col :span="24" style="font-size:16px;font-weight: bold;margin-bottom: 10px;">
            <h3>Send {{currOrder ? currOrder.guest_name : 'Unknown Guest'}} a  Special Offer</h3>
              <span> {{currOrder ? currOrder.guest_name : 'Unknown Guest'}} will have 24 hours to accept. In the meantime, your calendar will remain open</span>
            </el-col>
          </el-row>
          <el-form-item label="Listing"  prop="logical_room_id" class="form-item-wd">
            <el-select v-model="specialForm.listing_id" placeholder="Please Select A Listing"  class="input-size" @change="listingChange">
              <el-option
                v-for="item in logicRoomList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="18">
              <el-form-item label="Selected dates"  prop="dateRange">
                <div class="block" style="width: 100%">
                  <el-date-picker style="width: 70%"  class="input-size"
                                  v-model="specialForm.dateRange"
                                  type="daterange"
                                  align="right"
                                  unlink-panels
                                  range-separator="-"
                                  start-placeholder="Start Date"
                                  end-placeholder="End Date"
                                  format="yyyy-MM-dd"
                                  value-format="yyyy-MM-dd" :disabled="dateRangeDisabled" @change="dateRangeChange">
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="Guests"  prop="number_of_adults">
              <el-input-number v-model="specialForm.number_of_adults" :min="1" :max="1000" label="Guests" placeholder="Please Enter Guests"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10" >
              <el-form-item label="Subtotal" prop="total_price">
                <el-input placeholder="Please Enter Subtotal" v-model="specialForm.total_price">
                  <template slot="prepend">{{currency}}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="14" >
              <div style="height:95px;vertical-align:bottom;display:table-cell;padding-left: 18px;">Enter a subtotal that includes any cleaning or extra guest fees.This won't include service fees or applicable taxes.</div>
            </el-col>
          </el-row>

          <el-form-item style="text-align: center;"  v-if="!isBack">
            <el-button type="primary" @click="doSubmitSpecial" :disabled="specialBtnDisabled">Submit</el-button>
            <el-button @click="doCloseSpecial">Cancel</el-button>
          </el-form-item>

        </el-form>
        <div style="text-align: center;" v-if="isBack">
          <el-button type="primary" @click="doBackSpecialOffer">Withdraw Special Offer</el-button>
          <el-button @click="doCloseSpecial" :disabled="!isBack">Cancel</el-button>
        </div>
      </el-dialog>
      <!--******* 2020.03.03 外包加入  CODE START *******-->
    </div>
</template>
<script>
    //import moment from 'moment'
    import tree from '@/components/widgets/Tree'
    import Loading from '@/components/widgets/Loading'
    import Modal from '@/components/widgets/Modal'
    import fullCalendar from '@/components/widgets/RoomCalendar/RoomCalendar'
    import MenuSelect from '@/components/widgets/MenuSelect'
    import MenuSelectTemplate from '@/components/widgets/MenuSelect2'
    import ItemDetail from '@/components/widgets/ItemDetail'
    import CheckItem from '@/components/widgets/CheckItem'
    import ChatLangCtl from "@/components/widgets/ChatLangCtl"
    import swal from 'sweetalert'
    import {
        chatList,
        searchChat,
        getMessageList,
        sendMessage,
        seen,
        getRelatedInfo,
        setChatLabel,
        translateFromChat,
        translateMessage
    } from '@/api/chat'
    import {deleteModel, addModel, updateModel, searchModel} from '@/api/model'
    import {getRoomEvents} from '@/api/event'
    import {getIssues} from '@/api/auth'
    import {submitAction} from '@/api/task'

    //config
    import Config from '@/config'
    import {toTree, genUrlParams, matchAllImgSrc} from '@/utils'
    import columns from '@/config/columns'

    // catch
    import {loadHotTemplate, saveHotTemplate, deleteHotTemplate} from "@/cache";
    import Vue from 'vue'
    import VueClipboard from 'v-clipboard'
    import {itemMixin, checkListMixin} from '@/mixins/item'
    import vGallery from 'v-gallery';
    import moment from 'moment'//导入文件
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';

    Vue.prototype.$moment = moment;//赋值使用
    Vue.use(ElementUI);
    Vue.use(vGallery);
    Vue.use(VueClipboard)

    let makeIndex = (arr, key) => {
        let index = {}
        for (let i = 0; i < arr.length; i++) {
            index[arr[i][key]] = true
        }
        return index
    }

    export default {
        name: 'Chat',
        components: {
            Loading,
            Modal,
            fullCalendar,
            tree,
            MenuSelect,
            MenuSelectTemplate,
            ItemDetail,
            CheckItem,
            ChatLangCtl
        },
        mixins: [itemMixin, checkListMixin],
        created() {
            this.tags = Config.CHAT_TAGS
            if (this.$route.query.search) {
                this.searchKeyword = this.$route.query.type === 'Number' ? parseInt(this.$route.query.search) : this.$route.query.search
            }
            this.interval = null
            this.issue.created_by_user = this.$store.state.user
            this.hotTemplates = loadHotTemplate()
            this.groups = Config.GROUPS
        },
        mounted() {
            // 获取对话
            if (this.searchKeyword) {
                this.loadChat('all')
            } else {
                this.loadChat('new')
            }
            this.getReplyTemplate() // 获取回复模板
            this.initChatListWrapper()
            this.initMessageWrapper()
            this.initRelatedWrapper()
            clearInterval(this.interval)
            // 开启定时器轮询
            this.interval = window.setInterval(() => {
                this.loadChat(this.type, false)
            }, 30000)
        },
        destroyed() {
            if (this.interval) {
                clearInterval(this.interval)
            }
        },
        deactivated() {
            if (this.interval) {
                clearInterval(this.interval)
            }
        },
        data() {
            return {
                activeChatColor: '',

                loading: false,
                chatList: null,
                type: 'new',
                searchKeyword: '',
                currentChat: null,
                /**  外包加入 [2020.03.03 ]CODE START***/
                currOrder: null,
                currReservation:null,
                showButtons:false,
                submitLoading : false,
                refuseFormVisible:false,
                refuseFormLoading:false,
                refuseForm: { /*拒绝表单*/
                    decline_category:null,  //拒绝这个预约申请原因选择
                    decline_reason_public:null,//拒绝这个预约申请
                    decline_reason_private:null  //拒绝原因（非公开）
                },
                refuseRule: this.getRefuseRule(),
                /** 发送预准/发送特殊优惠 **/
                specialFormVisible:false,
                specialFormLoading:false,
                dateRangeDisabled: true,
                specialBtnDisabled: true,
                isBack:false, //是否撤回
                logicRoomList:[], //ListingId 列表
                currency:null,
                actionTitle : null,
                preApprovalBtnTxt:null,
                favourableBtnTxt:null,
                preApprovalData:null,  //未发送成功的 预准 PhysicalRoomSpecialOffer 数据
                favourableData:null,  //未发送成功的 特别优惠 PhysicalRoomSpecialOffer 数据
                specialBtnTxt:{
                    okDefaultTxt:'预准',
                    okBackTxt:'撤回预准',
                    offDefaultTxt:'特别优惠',
                    offBackTxt:'撤回特别优惠'
                },
                specialForm: { /*表单*/
                    id:null,
                    offer_type:null,	//字符串	目前只有两种选择：special_offer和 pre_approval。  当为pre_approval时，只有thread_id和listing_id为必填项目。
                    thread_id:null,	//	整数型	Special Offer关联的Thread的ID。
                    listing_id:null,	//	字符串	Special Offer关联的Listing的Listing ID。
                    dateRange:[],
                    start_date:null,	//	日期	Special Offer中指定的入住开始日期。
                    nights:null,	//	整数型	Special Offer中指定的入住夜数。最少为1。
                    number_of_adults:null,	//	整数型	指定的成人数量。
                    number_of_children:null,	//	整数型	指定的儿童数量。
                    number_of_infants:null,	//	整数型	指定的婴儿数量。婴儿数量不计入房源的最大入住人数限制。
                    total_price:null,	//	整数型	Special Offer的总价格。货币为房源Listing中指定的默认货币。
                    block_instant_booking:null	//	布尔值	是否在Special Offer有效期内阻止其他客人预定Special Offer中指定的日期。
                },
                specialRule: this.geSpecialRule(),
                /**  外包加入 [2020.03.03 ]CODE END***/
                //message
                showHtmlModal: false,
                showTemplateModal: false,
                loadingMessage: false,
                currentMsg: null,
                msgList: {},
                message: {
                    subject: '',
                    content: '',
                    to_address: '',
                    type: 'plain'
                },
                files: [],
                hotTemplates: [],
                templateData: {
                    'zh': null,
                    'jp': null,
                    'en': null,
                },
                templateDataTree: {
                    'zh': [],
                    'jp': [],
                    'en': [],
                },
                specialTreeData: [],
                language: 'zh',
                languageMenu: 'zh',

                //related
                relatedLoading: false,
                related: null,
                relatedRoomIndex: 0,
                relatedSubject: null,
                showCalendarModal: false,
                events: [],
                // issues
                showIssuesModal: false,
                issueRelatedMessage: '',
                issue: {
                    type: 'Dup. Order',
                    summary: '',
                    message: '',
                    type_code: ''
                },

                msgDetail: {
                    roomImg: null,
                    userImg: null,
                    title: '',
                    link: ''
                },
                currentMonth: moment().startOf('month'),
                priceData: [],
                currentChatView: 'NEW',

                // question
                questionnaires: [],
                questionnaireIndex: 0,

                // chat lang
                chatLangFlag: false,
                keyChatLang: "all",
                chatLang: "No",

                // translated
                translatedMap: {},
                sourceLang: 'en',
                targetLang: 'zh-cn'

            }
        },
        computed: {
            arrowCanPrevious() {
                let len = this.questionnaires.length
                return len > 1 && this.questionnaireIndex < len && this.questionnaireIndex > 0 ? true : false
            },
            arrowCanNext() {
                let len = this.questionnaires.length
                return len > 1 && this.questionnaireIndex < len - 1 ? true : false
            }
        },
        methods: {
            _checkList() {
                if (!this.related || !this.related.order || !this.related.order.length) return
                let newProps = {item: {id: this.related.order[0].id}}
                this.checkList(newProps, 'Order')
            },
            // 获取两个日期相隔天数
            _getNights(order) {
                return moment(order.checkout).diff(moment(order.checkin), 'days')
            },
            _getComments(data) {
                let comment = ''
                for (let key in data) {
                    return comment = data[key]
                }

            },
            initChatListWrapper() {
                let el = $('.chatonline')
                el.slimScroll().unbind("slimscroll")
                el.slimScroll({
                    height: '550px',
                    position: 'right',
                    size: "8px",
                    color: '#dcdcdc',
                });

                el.slimScroll().unbind("slimscroll").bind('slimscroll', (e, pos) => {
                    if (pos == 'bottom') {
                        this.loadMoreChat()
                    }
                });
            },
            openChatList() {
                $(".chat-left-aside").toggleClass("open-pnl");
                $(".open-panel i").toggleClass("fif fif-arrow-left");
            },
            search(e) {
                e.preventDefault()
                if (this.currentChatView === 'BOOKMARK') return
                this.loadChat('all')
            },
            loadBookmarkedChat() {
                clearInterval(this.interval)
                this.keyChatLang = 'all'
                this.interval = null
                this.loading = true
                this.currentChatView = 'BOOKMARK'
                searchModel('Chat', {
                    page_size: 999999,
                    search_keys: {
                        is_bookmarked: true
                    }
                }).then(res => {
                    this.loading = false
                    if (this.chatList && this.chatList.chat_list) {
                        this.chatList.chat_list = res.data.list
                    } else {
                        this.chatList = {}
                        this.chatList.chat_list = res.data.list
                    }

                }).catch(e => this.loading = false)
            },
            // 刷新对话
            reloadChat() {
                this.interval = window.setInterval(() => {
                    this.loadChat(this.type, false)
                }, 30000)
                this.loadChat(this.type)
            },
            // 获取聊天对话
            loadChat(type = 'new', showLoading = true) {
                this.type = type
                this.currentChatView = 'NEW'
                let mailbox = null
                if (this.$route.params.mailbox !== 'all') {
                    mailbox = this.$route.params.mailbox
                }
                let dataLoader = (res) => {
                    this.chatList = res.data
                    this.loading = false
                }

                if (showLoading) {
                    this.loading = true
                }

                if (this.type === 'all') {
                    searchChat(this.searchKeyword, mailbox, 1, this.keyChatLang)
                        .then(dataLoader)
                        .catch(() => {
                            this.loading = false
                        })
                } else {
                    this.searchKeyword = ''
                    chatList(this.type, mailbox, 1, this.keyChatLang)
                        .then(dataLoader)
                        .catch(() => {
                            this.loading = false
                        })
                }
            },
            // 上拉加载更多对话
            loadMoreChat() {
                let mailbox = null
                if (this.$route.params.mailbox !== 'all') {
                    mailbox = this.$route.params.mailbox
                }
                if (this.chatList && this.chatList.page.number < this.chatList.page.range) {
                    let dataLoader = (response) => {
                        this.loading = false
                        this.chatList.page = response.data.page
                        let index = makeIndex(this.chatList.chat_list, 'chat_id')
                        for (let i = 0; i < response.data.chat_list.length; i++) {
                            if (!index[response.data.chat_list[i]['chat_id']]) {
                                this.chatList.chat_list.push(response.data.chat_list[i])
                            }
                        }
                        this.$nextTick(() => {
                            this.initChatListWrapper()
                        })
                    }
                    this.loading = true
                    if (this.type !== 'all') {
                        chatList(this.type, mailbox, this.chatList.page.number + 1, this.keyChatLang)
                            .then(dataLoader)
                            .catch()
                    } else {
                        searchChat(this.searchKeyword, mailbox, this.chatList.page.number + 1, this.keyChatLang)
                            .then(dataLoader)
                            .catch()
                    }
                } else {

                }
            },
            formatTime(time) {
                return moment(time).fromNow()
            },
            // 标记对话类型
            mark(id, type) {
                updateModel('Chat', id, {is_replied: type === 'replied' ? true : false}).then(res => {
                    this.loadChat(this.type, false)
                }).catch(e => {
                })
            },
            //message
            initMessageWrapper(posDom) {
                let el = $('.chat-list')
                el.slimScroll().unbind("slimscroll")
                el.slimScroll({
                    height: '500px',
                    position: 'right',
                    size: "8px",
                    color: '#dcdcdc',
                    start: 'bottom',
                    scrollTo: posDom ? posDom : '999999px'
                });
                this.message.subject = ''
                el.slimScroll().unbind('slimscroll').bind('slimscroll', (e, pos) => {
                    if (pos === 'top') {
                        this.loadMoreMessage()
                    }

                });
            },
            genTagClass(msgList, tag) {
                return msgList.chat_info.label && msgList.chat_info.label.indexOf(tag.value) !== -1 ? tag.color : ''
            },
            setLabel(msg, label) {
                let chatLabel = msg.label ? msg.label.split(';') : []
                let index = -1
                for (let i in chatLabel) {
                    if (chatLabel[i] === label) {
                        index = i
                        break
                    }
                }
                if (index !== -1) {
                    chatLabel.splice(index, 1)
                } else {
                    chatLabel.push(label)
                }
                let newLabel = chatLabel.join(';')
                setChatLabel(msg.chat_id, newLabel).then(res => {
                    if (res.data.status === 'success') {
                        this.currentChat.label = newLabel
                        getMessageList(msg.chat_id)
                            .then((response) => {
                                response.data.msg_list.reverse()
                                this.msgList = response.data
                                this.loadingMessage = false
                            })
                            .catch(() => {
                                this.msgList = {}
                                this.loadingMessage = false
                            })
                    }
                })
            },
            // 获取chat message中的房东头像，房间图片
            getMsgDetail() {
                let msg = null
                this.msgList.msg_list.forEach(item => {
                    if (!item.send_from_funkey) {
                        msg = item;
                        return
                    }
                })

                if (msg && this.currentChat.platform === 'airbnb' && msg.html) {
                    let htmlDOM = $(msg.html)
                    let that = this

                    let hasSetUserImg = false
                    let hasSetRoomImg = false

                    htmlDOM.find('img').each(function () {
                        let src = $(this).attr('src')
                        let parent = $(this).parent()
                        let href = parent.attr('href')
                        if (href && href.indexOf('users') !== -1) {
                            that.msgDetail.userImg = src
                            hasSetUserImg = true
                        } else if (href && href.indexOf('rooms')) {
                            that.msgDetail.roomImg = src
                            that.msgDetail.link = parent.attr('href')

                            hasSetRoomImg = true
                        }
                    })

                    if (!hasSetUserImg) that.msgDetail.userImg = null
                    if (!hasSetRoomImg) {
                        that.msgDetail.roomImg = null
                        that.msgDetail.link = ''
                    } else {
                        this.related.room[this.relatedRoomIndex].room_photos.unshift({title: ' ', url: that.msgDetail.roomImg})
                    }

                    let hasSetTitle = false
                    htmlDOM.find('.headline').each(function () {
                        let next = $(this).next()
                        if (next.hasClass('subheadline')) {
                            that.msgDetail.title = $(this).text()
                            hasSetTitle = true
                        } else if (next.hasClass('midheadline')) {
                            that.msgDetail.title = $(this).text()
                            hasSetTitle = true
                        }
                    })
                    if (!hasSetTitle) that.msgDetail.title = ''
                } else {
                    this.msgDetail = {
                        title: '',
                        roomImg: null,
                        userImg: null,
                        link: ''
                    }
                }

                let agodaLink = null
                if (msg && this.currentChat.platform === 'agoda' && msg.html) {
                    let htmlDOM = $(msg.html)
                    let aTag = htmlDOM.find('a[title="Agoda.com"]')
                    agodaLink = aTag.attr('href')
                }

                // airbnb预准自动匹配PID
                if ((!this.related || !this.related.room.length) && (this.msgDetail.link || agodaLink)) {
                    let re = /memberID=(\d+)?/
                    let re1 = /&id=(\d+)/
                    let re2 = /rooms\/(\d+)?/
                    let lid = null
                    if (agodaLink) {
                        let match = agodaLink.match(re)
                        lid = match && match.length > 1 ? match[1] : null
                    } else {
                        let match1 = this.msgDetail.link.match(re1)
                        let match2 = this.msgDetail.link.match(re2)
                        lid = match1 && match1.length > 1 ? match1[1] : match2 && match2.length > 1 ? match2[1] : null
                    }


                    if (lid) {
                        searchModel('LogicalRoom', {
                            page_size: 999999,
                            search_keys: {
                                logical_room_id: lid
                            }
                        }).then(res => {
                            if (res.data.list.length) {
                                searchModel('PhysicalRoom', {
                                    page_size: 999999,
                                    search_keys: {
                                        physical_room_id: res.data.list[0].physical_room_id
                                    }
                                }).then(res => {
                                    if (res.data.list.length) {
                                        this.related = {}
                                        this.related.comment = null
                                        this.related.order = []
                                        this.related.room = res.data.list
                                    }
                                })
                            }

                        })
                    }
                }
            },
            // 点击对话获取对话详情
            showMessage(chat) {
                this.msgList = {}
                let chatId = chat.chat_id
                this.message.to_address = ''
                this.currentChat = chat
                this.related = null
                this.events = []
                this.showSubjectInput = false
                this.loadingMessage = true

                if (chat.is_new) {
                    this.seenMessage(chat)
                }

                if (this.$store.state.cancelToken) {
                    this.$store.state.cancelToken.cancel()
                }
                this.chatLangFlag = false
                this.chatLang = this._genChatLang(chat.language)
                getMessageList(chatId)
                    .then((response) => {
                        let newArr = []
                        for (let i = 0; i < response.data.msg_list.length; i++) {
                            let msg = response.data.msg_list[i]
                            msg.plain = msg.plain ? msg.plain : ""
                            let [msgText, translated] = msg.plain.split("<TRANSLATED>")
                            msg.originalPlain = msg.plain
                            if (translated) {
                                msg.plain = msgText
                                this.$set(msg, 'translated', translated)
                            } else {
                                this.$set(msg, 'translated', "")
                            }
                            newArr.unshift(msg)
                        }
                        response.data.msg_list = newArr
                        this.msgList = response.data
                        this.loadingMessage = false
                        this.showRelatedInformation(chatId)
                    })
                    .catch((e) => {
                        console.log(e)
                        this.msgList = null
                        this.loadingMessage = false
                    })
            },
            _genChatLang(lang) {
                let newLang = "NA"
                if (lang) {
                    lang = lang.indexOf("zh") !== -1 ? "zh-cn" : lang
                    newLang = ['zh-cn', 'ja', 'en'].indexOf(lang) !== -1 ? lang : "NA"
                }
                return newLang
            },
            // 下拉获取更多对话详情
            loadMoreMessage() {
                if (this.msgList && this.msgList.page.number < this.msgList.page.range) {
                    this.loadingMessage = true
                    const el = $('#' + this.msgList.msg_list[0].msg_id)
                    getMessageList(this.msgList.chat_info.chat_id, this.msgList.page.number + 1)
                        .then((response) => {
                            this.loadingMessage = false
                            this.msgList.page = response.data.page
                            //let index = makeIndex(this.msgList.msg_list, 'UID')
                            for (let i = 0; i < response.data.msg_list.length; i++) {
                                let msg = response.data.msg_list[i]
                                let [msgText, translated] = msg.plain.split("<TRANSLATED>")
                                msg.originalPlain = msg.plain
                                if (translated) {
                                    msg.plain = msgText
                                    this.$set(msg, 'translated', translated)
                                } else {
                                    this.$set(msg, 'translated', "")
                                }
                                this.msgList.msg_list.unshift(msg)
                            }

                            this.$nextTick(() => {
                                this.initMessageWrapper(el)
                            })

                        })
                        .catch(() => {
                            this.loadingMessage = false
                        })
                } else {

                }
            },
            toShowHtml(msg) {
                this.showHtmlModal = true
                this.currentMsg = msg
                let wrapper = $("#iframe-wrapper")
                let iframe = $(' <iframe id="message-html" frameborder="0"\n' +
                    '                            style=" width: 100%; height: 100%; ">\n' +
                    '                    </iframe>')
                wrapper.html(iframe)
                // let iwindow = iframe.contentWindow
                iframe.contents().find('body').html(this.formatHTML(msg.html))
            },
            formatHTML(html) {
                return html ? html
                        .replace(/<style[^>]*>/g, '<div style="display: none;">').replace(/<\/style>/g, '</div>')
                        .replace(/<script[^>]*>/g, '<div style="display: none;">').replace(/<\/script>/g, '</div>')
                    : ''
            },
            formatText(text) {
                return text ? text.split('\n') : []
            },
            showFileWindow() {
                $('#chat-file').click()
            },
            // 点击发送
            sendMessage(e) {
                if ((this.msgList || this.message.to_address.trim()) && !this.loadingMessage) {


                    if (this.message.content.match(/\{.*\}/g)) {
                        return $.toast({
                            heading: 'error',
                            text: 'Please replace the information in the template with the corresponding information.',
                            position: 'top-right',
                            loaderBg: '#ff6849',
                            icon: 'error',
                        });
                    }


                    this.loadingMessage = true
                    let param = new FormData(); //创建form对象
                    for (let i = 0; i < this.files.length; i++) {
                        param.append(this.files[i].name, this.files[i], this.files[i].name) // 通过append向form对象添加数据
                    }

                    if (!this.message.subject) {
                        this.message.subject = "Re:" + this.msgList.msg_list[this.msgList.msg_list.length - 1].subject
                    }

                    param.append('chat_id', this.msgList ? this.msgList.chat_info.chat_id : 1)
                    param.append('subject', this.message.subject)
                    param.append('to_address', this.message.to_address)
                    param.append('content', this.message.content)
                    param.append('type', this.message.type)

                    sendMessage(param)
                        .then((res) => {
                            this.loadingMessage = false
                            if (this.state === 'new' && this.msgList) {
                                let column = this.chatList.chat_list.findIndex((e) => (e.chat_id === this.msgList.chat_info.chat_id))
                                if (column > 0) {
                                    this.chatList.chat_list.splice(column, 1)
                                }
                            }
                            if (res.data.status == 'success') {
                                this.message.subject = ''
                                this.message.content = ''
                                $.toast({
                                    heading: 'success',
                                    position: 'top-right',
                                    icon: 'success',
                                });
                            } else if (res.data.status == 'fail') {
                                $.toast({
                                    heading: 'error',
                                    text: res.data.reason,
                                    position: 'top-right',
                                    loaderBg: '#ff6849',
                                    icon: 'error',
                                });
                            } else {
                                $.toast({
                                    heading: 'fail',
                                    position: 'top-right',
                                    loaderBg: '#ff6849',
                                    icon: 'error',
                                });
                            }

                            if (this.msgList) {
                                getMessageList(this.msgList.chat_info.chat_id)
                                    .then((response) => {
                                        response.data.msg_list.reverse()
                                        this.msgList = response.data
                                        this.loadingMessage = false
                                    })
                                    .catch(() => {
                                        this.loadingMessage = false
                                    })
                            }

                        })
                        .catch(() => {
                            this.loadingMessage = false
                            this.$message({
                                message: 'Failure',
                                type: 'error'
                            })
                        })
                }
                e.preventDefault()
            },
            getFile(event) {
                this.files = event.target.files
            },
            // 点击对话已读
            seenMessage(chat) {
                seen(chat.chat_id)
                    .then(() => {
                        chat.is_new = false
                    }).then(() => this.$store.dispatch('setMailNum'))
            },
            // related info
            initRelatedWrapper() {
                let el = $('.chat-aside2')
                el.slimScroll({
                    height: '550px',
                    position: 'right',
                    size: "8px",
                    color: '#dcdcdc',
                    // scrollTo: '50px'
                });
            },
            handleURL(str) {
                let objArr = JSON.parse(str.replace(/\'/g, '"'))
                let imagesURLs = []
                objArr.forEach(item => {
                    imagesURLs.push({id: item.id, url: item.url.url, title: ' '})
                })
                return imagesURLs
            },
            /**
             *  获取截止日期和起始日期之间的天数
             * */
            getDays(startDate, endDate){
                const days = moment(endDate).diff(moment(startDate), 'days')
                //console.log(endDate+" - "+startDate+ "="+ days);
                return days;
            },
            showRelatedInformation(chatId) {
                this.related = null
                this.currOrder = null;
                this.currReservation = null;
                this.showButtons = false;
                this.activeChatColor = ''
                //  this.newRelatedSubject = ''
                this.relatedLoading = true
                getRelatedInfo(chatId)
                    .then((response) => {
                        this.relatedLoading = false
                        this.related = response.data
                        this.relatedRoomIndex = 0
                        this.currOrder = (this.related.order && this.related.order.length>0) ? this.related.order[this.relatedRoomIndex] : null;
                        if(this.currOrder){
                            const checkin = this.currOrder.checkin;
                            const checkout = this.currOrder.checkout;
                            const days = this.getDays(checkin, checkout);
                            this.currOrder.days = days;
                        }
                        this.currReservation = (this.related.reservations && this.related.reservations.length>0) ? this.related.reservations[this.relatedRoomIndex] : null;
                        const sign = "airbnb://";
                        if((this.currentChat &&  this.currentChat.addr && this.currentChat.addr.startsWith(sign)) &&
                            (this.currReservation && this.currReservation.reservation_code == 'NOT_AVAILABLE')){  //来源于 airbnb 和  reservation_code= NOT_AVAILABLE 才展示接受/拒绝/预准/特别优惠按钮
                            this.showButtons = true;
                            this.switchSpecialBtnTxt();
                        }
                        this._resetRelated()
                        this.$nextTick(() => {
                            this.initRelatedWrapper()
                        })
                    })
                    .catch(() => {
                        this.relatedLoading = false
                    })
            },
            _resetRelated() {
                if (this.related && this.related.room[this.relatedRoomIndex]) {
                    this.activeChatColor = this.related.room[this.relatedRoomIndex].color_code
                    this.message.content = this.message.content.replace(/\{(.*?)\}/g, ($1, $2) => {
                        if (this.related.room[this.relatedRoomIndex][$2]) {
                            return this.related.room[this.relatedRoomIndex][$2]
                        } else {
                            return $1
                        }
                    })
                    this.related.room[this.relatedRoomIndex].room_photos = this.handleURL(this.related.room[this.relatedRoomIndex].room_photos_hook)
                    this.getMsgDetail()
                    searchModel('MessageTemplate', {
                        page_size: 999999,
                        search_keys: {
                            pid: this.related.room[this.relatedRoomIndex].physical_room_id
                        }
                    }).then(res => {
                        this.specialTreeData = toTree(JSON.parse(JSON.stringify(res.data.list)))
                    })
                }
            },
            toShowOrder() {
                if (this.related && this.related.order && this.related.order.length) {
                    this.model = 'Order'
                    this.item = []
                    this.defaultColumns = columns[this.model]
                    this.editItem({item: {id: this.related.order[0].id}})
                    this.showModal = true
                }

            },
            toShowRoom() {
                if (this.related && this.related.room.length) {
                    this.model = 'PhysicalRoom'
                    this.defaultColumns = columns[this.model]
                    this.item = []
                    this.editItem({item: {id: this.related.room[this.relatedRoomIndex].id}})
                    this.showModal = true
                }
            },
            toShowCalendarModal() {
                if (this.related && this.related.room.length) {
                    this.showCalendarModal = true
                    this.showRoomCalendar(this.related.room[this.relatedRoomIndex].physical_room_id)
                }
            },
            toShowQuestionnaire() {
                if (this.related && this.related.order && this.related.order.length) {
                    let order = this.related.order[0]
                    let room = this.related.room[0]

                    if (Config.ROOM_AREA_JAPAN.indexOf(room.room_area.trim()) !== -1) {
                        this._handleQuestion("GuestRegistration", order)
                    } else if (Config.ROOM_AREA_THAILAND.indexOf(room.room_area.trim()) !== -1) {
                        this._handleQuestion("ThailandGuestRegistration", order)
                    }

                }
            },
            changeItem(dir) {
                this.questionnaireIndex = dir === "previous" ? this.questionnaireIndex - 1 : this.questionnaireIndex + 1
                let item = this.questionnaires[this.questionnaireIndex]
                this.model = item.model
                this.defaultColumns = columns[this.model]
                this.item = []
                this.editItem({item: {id: item.id}})
            },
            _handleQuestion(model, order) {
                searchModel(model, {
                    search_keys: {
                        reservation_code__icontains: order.reservation_code
                    }
                }).then(res => {
                    if (res.data.list.length) {
                        this.model = model
                        this.questionnaires = res.data.list.map(item => Object.assign({}, item, {model: model}))
                        this.questionnairesIndex = 0
                        this.defaultColumns = columns[this.model]
                        this.item = []
                        this.editItem({item: {id: this.questionnaires[0].id}})
                        this.showModal = true
                    } else {
                        if (model === "GuestRegistration") {
                            let params = {
                                reservation_code: order.reservation_code,
                                guest_name: order.guest_name,
                                checkin: order.checkin,
                                checkout: order.checkout,
                                platform: order.platform
                            }
                            if (order.checkin_time) {
                                params["checkin_time"] = order.checkin_time
                            }
                            if (order.checkout_time) {
                                params["checkout_time"] = order.checkout_time
                            }
                            swal({
                                title: "No Questionnaire",
                                text: "Do you want to add Questionnaire?",
                                icon: "warning",
                                dangerMode: true,
                                buttons: true,
                            }).then(will => {
                                if (will) {
                                    setTimeout(function () {
                                        window.open("https://registration.heyakun.com/?" + genUrlParams(params))
                                    }, 500);
                                }
                            })
                        } else {
                            let params = {
                                reservation_code: order.reservation_code,
                                guest_name: order.guest_name,
                                checkin: order.checkin,
                                guest_contact: order.guest_contact
                            }
                            swal({
                                title: "No Questionnaire",
                                text: "Do you want to add Questionnaire?",
                                icon: "warning",
                                dangerMode: true,
                                buttons: true,
                            }).then(will => {
                                if (will) {
                                    setTimeout(function () {
                                        window.open("https://registration.heyakun.com/thailand/?" + genUrlParams(params))
                                    }, 500);
                                }
                            })
                        }
                    }
                })
            },
            showRoomCalendar(id) {
                this.events = []
                searchModel("PriceCalendar", {
                    "search_keys": {"physical_room__physical_room_id": id},
                    "page_size": 99999,
                }).then(res => {
                    this.priceData = res.data.list
                })

                getRoomEvents(id, 'only', id).then((response) => {
                    let evt = response.data.events
                    this.events = []
                    for (let i = 0; i < evt.length; i++) {
                        let css = 'bg-info'
                        let start = evt[i].start
                        let end = evt[i].end
                        if (this.related.order && this.related.order.length > 0) {
                            this.currentMonth = moment(this.related.order[0].checkin)
                            for (let j = 0; j < this.related.order.length; j++) {
                                if (this.related.order[j].logical_room_id === evt[i].logical_room_id &&
                                    this.related.order[j].checkin === start &&
                                    this.related.order[j].checkout === end
                                ) {
                                    css = 'bg-danger'
                                    break
                                }
                            }
                        }
                        this.events.push({
                            start: start,
                            end: end,
                            title: evt[i].title,
                            cssClass: css
                        })
                    }
                })
            },
            copyMediaLink(link) {
                this.$clipboard(link)
                $.toast({
                    heading: 'Success',
                    position: 'top-right',
                    icon: 'success'
                })
            },
            showTemplate() {
                this.showTemplateModal = true
            },
            // issues
            // 弹框显示issue
            toShowIssue(msg) {
                this.issue.type = 'Dup. Order'
                this.issue.summary = ''
                this.issue.message = ''
                this.issue.type_code = ''
                this.issueRelatedMessage = msg.plain
                this.issue.related_message = msg.msg_id
                this.issue.related_chat = this.currentChat.chat_id
                this.$nextTick(() => {
                    this.showIssuesModal = true
                })
            },
            toTranslate(msg) {
                let [msgText, translated] = msg.originalPlain.split("<TRANSLATED>")
                if (!translated) {
                    translateFromChat(msg.msg_id).then(res => {
                        for (let i = 0; i < this.msgList.msg_list.length; i++) {
                            let tmpMsg = this.msgList.msg_list[i]
                            if (tmpMsg.msg_id === msg.msg_id) {
                                tmpMsg.translated = res.data.translated_text
                                break;
                            }
                        }
                    })
                }
            },
            getIssueTip() {
                if (!this.issue.type_code.trim().length) {
                    return $.toast({
                        heading: 'Wrong',
                        text: 'Please type case code',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error'
                    });
                }

                searchModel('IssueReccomendation', {
                    page: 1,
                    search_keys: {
                        type_code: this.issue.type_code
                    }
                }, null).then(res => {
                    if (res.data.list.length) {
                        swal('', res.data.list[0].recommendation, 'info')
                    } else {
                        $.toast({
                            heading: 'Wrong',
                            text: 'Not matched case',
                            position: 'top-right',
                            loaderBg: '#ff6849',
                            icon: 'error'
                        });
                    }
                })
            },
            addIssue() {
                let currentGroup = null
                this.groups.forEach(item => {
                    if (this.$store.state.groups.indexOf(item.value) !== -1) {
                        currentGroup = item.value
                    }
                })

                if (this.issue.related_chat && this.issue.summary.trim() && this.issue.message.trim()) {

                    if (currentGroup) {
                        this.issue.current_group = currentGroup
                    }

                    this.issue.current_user = this.$store.state.user

                    addModel('issues', this.issue).then(res => {
                        swal("success", "", "success")
                        this.showIssuesModal = false
                        if (String(this.currentChat.label).indexOf(this.issue.type) === -1) {
                            this.setLabel(this.currentChat, this.issue.type)
                        }
                        this.$store.dispatch("setIssueNum")
                    })
                } else {
                    $.toast({
                        heading: 'You must fill fields with *',
                        text: '',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    });
                }
            },
            // reply template
            getCurrentNode(node) {
                this.currentNode = node
            },
            // 转换数据结构
            selectTemplateFromMenu(content) {
                this.message.content = content.replace(/\{(.*?)\}/g, ($1, $2) => {
                    if (this.related && this.related.room[0] && this.related.room[0][$2]) {
                        return this.related.room[0][$2]
                    } else if (this.related && this.related.order[0] && this.related.order[0][$2]) {
                        return this.related.order[0][$2]
                    } else {
                        return $1
                    }
                })


            },
            // 当选择某个模板时回调
            selectTemplate() {
                if (this.currentNode) {
                    if (this.currentNode.node.original.node_type === 'group') {
                        $.toast({
                            heading: 'Please chose template',
                            position: 'top-right',
                            loaderBg: '#ff6849',
                            icon: 'error',
                        })
                    } else {
                        this.message.content = this.currentNode.node.text

                        this.message.content = this.message.content.replace(/\{(.*?)\}/g, ($1, $2) => {
                            if (this.related && this.related.room[0] && this.related.room[0][$2]) {
                                return this.related.room[0][$2]
                            } else if (this.related && this.related.order[0] && this.related.order[0][$2]) {
                                return this.related.order[0][$2]
                            } else {
                                return $1
                            }
                        })

                        this.hotTemplates = saveHotTemplate(this.currentNode.node.text)
                        this.showTemplateModal = false
                    }
                } else {
                    $.toast({
                        heading: 'Please chose template',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    })
                }
            },
            // 点击弹框显示模板
            clickTemplate(template) {
                // this.hotTemplates = saveHotTemplate(template)
                this.message.content = template.replace(/\{(.*?)\}/g, ($1, $2) => {
                    if (this.related && this.related.room[0] && this.related.room[0][$2]) {
                        return this.related.room[0][$2]
                    } else if (this.related && this.related.order[0] && this.related.order[0][$2]) {
                        return this.related.order[0][$2]
                    } else {
                        return $1
                    }
                })
            },
            // 切换回复模板语言
            changeTemplate(lang) {
                this.language = lang
            },
            // 获取所有回复模板
            getReplyTemplate() {
                searchModel('MessageTemplate', {
                    page_size: 999999,
                    search_keys: {}
                }).then(res => {
                    if (res.data.list.length) {
                        let data = {}
                        res.data.list.forEach(item => {
                            (data[item.lang] || (data[item.lang] = [])).push(item)
                        })
                        this.templateData = data

                        this.templateDataTree['zh'] = toTree(JSON.parse(JSON.stringify(this.templateData['zh'])))[0].children
                        this.templateDataTree['jp'] = toTree(JSON.parse(JSON.stringify(this.templateData['jp'])))[0].children
                        this.templateDataTree['en'] = toTree(JSON.parse(JSON.stringify(this.templateData['en'])))[0].children

                    } else {
                        this.createTemplate({
                            id: '#' + this.language,
                            icon: 'fif fif-world',
                            original: {
                                parent: '#',
                                node_type: 'group',
                            },
                            text: this.language
                        })
                    }
                })
            },
            // 点击创建回复模板
            createTemplate(node) {
                let item = {
                    lang: this.language,
                    mid: node.id,
                    parent: node.original.parent,
                    node_type: node.original.node_type,
                    icon: node.icon,
                    text: node.text
                }
                addModel('MessageTemplate', item).then(res => {
                    this.getReplyTemplate(this.language)
                }).catch(e => {
                    this.getReplyTemplate(this.language)
                })
            },
            // 点击删除回复模板
            deleteTemplate(node) {
                if (node.original.pk) {
                    swal({
                        title: "Are you sure?",
                        text: "Remove this item",
                        icon: "warning",
                        dangerMode: true,
                        buttons: true,
                    }).then((willDelete) => {
                        if (willDelete) {
                            this.tableLoading = true
                            deleteModel('MessageTemplate', node.original.pk).then(res => {
                                this.tableLoading = false
                                swal("success", "", "success")
                                this.getReplyTemplate(this.language)
                                this.hotTemplates = deleteHotTemplate(node.text)
                            }).catch(e => {
                                this.tableLoading = false
                                this.getReplyTemplate(this.language)
                            })
                        }
                    })
                }
            },
            // 点击修改回复模板
            updateTemplate(node, oldText) {
                if (node.original.pk) {
                    updateModel('MessageTemplate', node.original.pk, {
                        'text': node.text
                    }).then(res => {
                        this.tableLoading = false
                        this.getReplyTemplate(this.language)
                        this.hotTemplates = deleteHotTemplate(oldText)
                    }).catch(e => {
                        this.getReplyTemplate(this.language)
                    })
                }
            },
            // 点击收藏或取消收藏
            toggleBookmark(bookmarked) {
                if (this.currentChat) {
                    updateModel('Chat', this.currentChat.chat_id, {
                        'is_bookmarked': bookmarked
                    }).then(res => {
                        this.currentChat.is_bookmarked = bookmarked

                        if (this.currentChatView === 'BOOKMARK') {
                            this.loadBookmarkedChat()
                            this.msgList = {}
                            this.related = null
                            this.currentChat = null
                        }

                    }).catch(e => {

                    })
                }
            },
            // 点击翻译对话详情
            translateMessage() {
                if (this.sourceLang === this.targetLang) return;
                if (!this.message.content.trim()) return;
                translateMessage({source: this.sourceLang, target: this.targetLang, text: this.message.content})
                    .then(res => {
                        this.message.content = res.data.translated_text
                    })
            },
            /**------- 2020.03.03 外包 CODE START ------**/
            getCustRulesConfig(){
                return {
                    intValid: function(label, min, max){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseInt(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an integer value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an integer value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    callback();
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }
                        };
                        return intValidFun;
                    },
                    floatValid: function(label, min, max,custCb){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseFloat(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an float value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an float value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    if(custCb){
                                        custCb(rule, value, callback);
                                    }else{
                                        callback();
                                    }
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }

                        };
                        return intValidFun;
                    },
                };
            },
            getRefuseRule(){
                const _this = this;
                //const custRulesCfg = this.getCustRulesConfig();
                return {
                    decline_category:[
                        { required: true, message: '请选择为什么拒绝这个预约申请', trigger: 'change'}
                    ],
                    decline_reason_public:[
                      { required: true, message: '请输入拒绝原因（公开）', trigger: 'blur' },
                      { min: 1, max: 300, message: '1 到 300 字符长度', trigger: 'blur' }
                    ],
                    decline_reason_private:[
                        { required: true, message: '请输入拒绝原因（非公开）', trigger: 'blur' },
                        { min: 1, max: 300, message: '1 到 300 字符长度', trigger: 'blur' }
                    ]
                };
            },
            /**
             * 发送预准/发送特殊优惠 表单验证
             * */
            geSpecialRule(){
                const _this = this;
                const custRulesCfg = this.getCustRulesConfig();
                const priceValid = custRulesCfg.floatValid('Subtotal',10,100000);
                let dateRangValid = (rule, value, callback) => {
                    let _start_date = this.specialForm.start_date;
                    console.log("dateRangValid...");
                    console.log(this.specialForm);
                  //  console.log(_dateRange);
                    if (!_start_date) {
                        callback(new Error('Please Selected dates'));
                    } else {
                        callback();
                    }
                };

                return {
                    listing_id:[
                        { required: true, message: 'Please Select A Listing', trigger: 'change'}
                    ],
                    dateRange:[
                        { required: true, validator: dateRangValid, trigger: 'blur'}
                    ],
                    number_of_adults:[
                        { required: true, message: 'Please Enter Guests', trigger: 'blur' }
                    ],
                    total_price:[
                        { required: true, validator: priceValid, trigger: 'blur' }
                    ],
                };
            },
            /**
             * 当选择了 Listing 时，日期可选择
             * */
            listingChange(){
                this.dateRangeDisabled = false;
            },
            dateRangeChange(value){
                window.setTimeout(()=>{
                  this.loadCalendar(value);
                },50);
            },
            loadCalendar(dateRange){
                const _this = this;
                const _listing_id = this.specialForm.listing_id;
                if(!dateRange || dateRange.length == 0){
                    _this.specialBtnDisabled = true;
                    _this.$message.error('Duplicate date selected!');
                    return;
                }
                const _firstDate = dateRange[0];
                const _lastDate = dateRange[1];
                let firstDate = moment(_firstDate).format('YYYY-MM-DD');
                let lastDate = moment(_lastDate).format('YYYY-MM-DD');
                this.specialFormLoading = true;
                this.logicRoomList = [];
                searchModel('ICalendarNoConflict', {
                    page_size: 999999,
                    search_keys: {},
                    raw_filter:{
                        physical_room__logical_room__logical_room_id: _listing_id,
                        check_in_date__lte: firstDate,
                        check_out_date__gt: lastDate
                    }
                }).then(res => {
                    this.specialFormLoading = false
                    const list = res.data.list;
                    if(!list || list.length == 0){
                        _this.specialBtnDisabled = false;
                    }else{
                        _this.specialBtnDisabled = true;
                        _this.$message.error('Duplicate date selected!');
                    }
                }).catch(e =>{
                    this.specialFormLoading = false;
                    console.log(e);
                    _this.$message.error('通过API从服务器获取 ICalendarNoConflict 数据失败!');
                })
            },
            /**
             * 加载 LogicRoomList
             * */
            loadLogicRoomList(cb){
                const _this = this;
                const _hostName = this.currReservation.host_name;
                this.specialFormLoading = true;
                this.logicRoomList = [];
                searchModel('PhysicalRoomListing', {
                    page_size: 999999,
                    search_keys: {},
                    raw_filter:{
                        logical_room__managing_host__host_name: _hostName
                    }
                }).then(res => {
                    this.specialFormLoading = false
                    const list = res.data.list;
                    if(cb) cb();
                    if(!list || list.length == 0) return;
                    this.logicRoomList = list.map(item => {
                        return {value:item.listing_id, label:item.name};
                    });
                }).catch(e =>{
                    this.specialFormLoading = false;
                    console.log(e);
                    _this.$message.error('通过API从服务器获取 Listing 数据失败!');
                })
            },
            switchSpecialBtnTxt(){ //根据状态切换按钮文字
                const specialArr = this.currReservation.special_offers;
                let _preApprovalBtnTxt = this.specialBtnTxt.okDefaultTxt;
                let _favourableBtnTxt = this.specialBtnTxt.offDefaultTxt;
                let _preApprovalData = null;
                let _favourableData = null;
                if(specialArr && specialArr.length > 0){
                  let _arr = this._getBackArr('pre_approval');
                  if (_arr && _arr.length>0){
                      _preApprovalBtnTxt = this.specialBtnTxt.okBackTxt;
                      _preApprovalData = _arr[0];
                  }else{
                      _preApprovalData = this._getUnSentData('pre_approval');
                  }
                  _arr =  this._getBackArr('special_offer');
                  if(_arr && _arr.length>0){
                      _favourableBtnTxt = this.specialBtnTxt.offBackTxt;
                      _favourableData = _arr[0];
                  }else{
                      _favourableData = this._getUnSentData('special_offer');
                  }

                }
                this.preApprovalBtnTxt = _preApprovalBtnTxt;
                this.favourableBtnTxt = _favourableBtnTxt;
                this.preApprovalData = _preApprovalData;
                this.favourableData = _favourableData;
            },
            _getUnSentData(offType){
                const specialArr = this.currReservation.special_offers;
                let _backArr = specialArr.filter(item => {
                    return (item.offer_type==offType && (!item.is_withdrawn && !item.is_sent));
                });
                return (_backArr && _backArr.length>0) ? _backArr[_backArr.length-1] : null;
            },
            _getBackArr(offType){
                const specialArr = this.currReservation.special_offers;
                let _backArr = specialArr.filter(item => {
                    return (item.offer_type==offType && (!item.is_withdrawn && item.is_sent)); //测试完后，记得还原
                });
                return _backArr;
            },
            doConfirm(msg,cb){
                //'此操作将永久删除该文件, 是否继续?'
                const _msg = msg || '确定执行当前操作吗？';
                this.$confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(cb) cb();
                });
            },
            /**
             * 接受
             * */
            doAccept(){
                this._doAccept();
            },
            /**
             * 接受 或 拒绝
             * */
            _doAccept(modelName,actionName,pkId,cb){
              const _this = this;
              const _model = modelName || "Reservation";
              const _actionName = actionName || "accept_reservation";
              const _id = pkId || this.currReservation.id;
                if(!_id){
                    _this.$message.error(_model+' id is null,Please Check Data...!');
                    return;
                }
                const doAction = ()=>{
                    submitAction(_model, _id, _actionName)
                        .then(res => {
                            _loading = false;
                            _this.$notify({
                                title: 'Success',
                                message: _model+':'+_id+' call API:'+_actionName+' succeeded !',
                                type: 'success'
                            });
                            _this.showButtons = false;
                            if(cb) cb();
                        }).catch(reason => {
                        _loading = false;
                        console.log("deleteModel Failure...");
                        console.error(reason);
                        let errMsg = reason.data || reason.statusText;
                        _this.$notify.error({
                            title: 'Error',
                            message: 'API:'+_actionName+'  call error ,Error Reason:['+errMsg+']',
                            duration:4000,
                            onClose:()=>{
                                console.log("$notify.error.onClose");
                                if(cb) cb();
                            }
                        });

                    });
                };
                _loading = true;
                let _loading = null;
                if(_actionName && (_actionName == "accept_reservation" //接受 ，撤回优惠 撤回预准  ActionTask
                    || _actionName == "withdrawal_special_offer")){
                    _loading = _this.submitLoading;
                    const msg = this._getMsg(_actionName);
                    this.doConfirm(msg,doAction);
                }else{
                    _loading = _this.refuseFormLoading;
                    if(_model == 'PhysicalRoomSpecialOffer')  _loading = _this.specialFormLoading;
                    doAction();
                }
            },
            _getMsg(_actionName){
                let msg = "确定接受预约申请吗？";
                if(_actionName == 'withdrawal_special_offer'){
                    msg = "确定撤回吗？";
                }
                return msg;
            },
            /**
             * 拒绝
             * */
            doRefuse(){
                console.log("doRefuse...");
                this.refuseFormVisible = true;
                if(this.$refs['refuseForm']) this.$refs['refuseForm'].resetFields();
            },
            _fillSpecialForm(modifyData){
                if(this.$refs['specialForm']) this.$refs['specialForm'].resetFields();
                if(modifyData){
                    const start_date = modifyData.start_date;
                    const nights = modifyData.nights;
                    let end_date = moment(start_date).add(nights, 'd');
                    const _end_date = moment(end_date).format('YYYY-MM-DD');
                    const _dateRange = [start_date, _end_date];

                    const {id,offer_type,thread_id,listing_id,number_of_adults,number_of_children,number_of_infants,total_price,block_instant_booking} = modifyData;

                    this.specialForm = {
                        id:id,
                        offer_type: offer_type,    //字符串   目前只有两种选择：special_offer和 pre_approval。  当为pre_approval时，只有thread_id和listing_id为必填项目。
                        thread_id: thread_id, //  整数型 Special Offer关联的Thread的ID。
                        listing_id: listing_id,    //  字符串 Special Offer关联的Listing的Listing ID。
                        dateRange: _dateRange,
                        start_date: start_date,    //  日期  Special Offer中指定的入住开始日期。
                        nights: nights,    //  整数型 Special Offer中指定的入住夜数。最少为1。
                        number_of_adults: number_of_adults,  //  整数型 指定的成人数量。
                        number_of_children: number_of_children,    //  整数型 指定的儿童数量。
                        number_of_infants: number_of_infants, //  整数型 指定的婴儿数量。婴儿数量不计入房源的最大入住人数限制。
                        total_price: total_price,   //  整数型 Special Offer的总价格。货币为房源Listing中指定的默认货币。
                        block_instant_booking: block_instant_booking  //  布尔值 是否在Special Offer有效期内阻止其他客人预定Special Offer中指定的日期。
                    }
                }else{

                    this.specialForm = {
                        id:null,
                        offer_type: null,    //字符串   目前只有两种选择：special_offer和 pre_approval。  当为pre_approval时，只有thread_id和listing_id为必填项目。
                        thread_id: null, //  整数型 Special Offer关联的Thread的ID。
                        listing_id: null,    //  字符串 Special Offer关联的Listing的Listing ID。
                        dateRange: [],
                        start_date: null,    //  日期  Special Offer中指定的入住开始日期。
                        nights: 0,    //  整数型 Special Offer中指定的入住夜数。最少为1。
                        number_of_adults: null,  //  整数型 指定的成人数量。
                        number_of_children: null,    //  整数型 指定的儿童数量。
                        number_of_infants: null, //  整数型 指定的婴儿数量。婴儿数量不计入房源的最大入住人数限制。
                        total_price: 0,   //  整数型 Special Offer的总价格。货币为房源Listing中指定的默认货币。
                        block_instant_booking: null  //  布尔值 是否在Special Offer有效期内阻止其他客人预定Special Offer中指定的日期。
                    }
                }

            },
            _doApprovalOrSpecial(offerType, modifyData){
                const _this = this;
                this.loadLogicRoomList(()=>{
                    _this.specialFormVisible = true;
                    if(!_this.specialForm.id) _this.dateRangeDisabled = true;
                    this._fillSpecialForm();
                    if(this.currOrder){
                        this.currency = this.currOrder.currency;
                    }

                    if(modifyData){
                        this._fillSpecialForm(modifyData);
                        this.specialBtnDisabled = false;
                        this.dateRangeDisabled = false;
                    }else{
                        this.specialForm.offer_type = offerType;
                        const _addr = this.currentChat.addr;
                        let _thread_id = null;
                        const sign = "airbnb://";
                        console.log(_addr && _addr.startsWith(sign));
                        if(_addr && _addr.startsWith(sign)){
                            _thread_id = _addr.substring(_addr.indexOf(sign)+sign.length, _addr.length);
                        }
                        this.specialForm.thread_id = _thread_id;
                        if(this.currOrder){
                            this.specialForm.total_price = this.currOrder.total_cost;
                        }
                    }
                });
            },
            /**
             * 预准
             * */
            doApproval(){
                this.actionTitle = this.preApprovalBtnTxt;
                if(this.preApprovalBtnTxt == this.specialBtnTxt.okDefaultTxt){ //预准
                    console.log("doApproval[预准]...");
                    this._doApprovalOrSpecial('pre_approval',this.preApprovalData);
                }else{ //撤回预准
                    console.log("doApproval 撤回预准...");
                    this._doBackSpecialOffer(this.preApprovalData);
                }
            },
            doBackSpecialOffer(){
                this._doBackSpecialOffer(this.favourableData);
            },
            _doBackSpecialOffer(modData){
                if(!modData || !modData.id){
                    this.$message.error('PhysicalRoomSpecialOffer id is null!');
                    return;
                }
                const pkId = modData.id;
                this._doAccept('PhysicalRoomSpecialOffer','withdrawal_special_offer',pkId,()=>{
                    //this.$router.go(0);
                    this.doCloseSpecial();
                    this.showButtons = false;
                });
            },
            /**
             * 特别优惠
             * */
            doSpecial(){
                this.isBack = false;
                this.actionTitle = this.favourableBtnTxt;
                if(this.favourableBtnTxt == this.specialBtnTxt.offBackTxt){
                    this.isBack = true;
                }
                this._doApprovalOrSpecial('special_offer',this.favourableData);
                console.log(this.favourableBtnTxt);
                // if(this.favourableBtnTxt == this.specialBtnTxt.offDefaultTxt){
                //     console.log(this.favourableData);
                //     console.log("doSpecial[特别优惠]...");
                //     this._doApprovalOrSpecial('special_offer',this.favourableData);
                // }else{
                //     this.isBack = true;
                //     console.log("doSpecial 撤回特别优惠...");
                // }
            },
            /**
             * 提交拒绝原因
             * */
            doSubmitRefuse(){
                const _this = this;
                const _model = "Reservation";
                const _actionName = "decline_reservation";
                const _id = this.currReservation.id;
                if(!_id){
                    _this.$message.error(this.model+' id is null,Please Check Data...!');
                    return;
                }

                this.$refs['refuseForm'].validate((valid) => {
                    if (valid) {
                        _this.refuseFormLoading = true;
                       updateModel(_model, _id, this.refuseForm).then(res =>{
                           _this.refuseFormLoading = false;
                           _this.$message({
                               type: 'info',
                               message: 'Save Data Success!'
                           });
                          _this._doAccept(null,_actionName,null,()=>{
                              _this.showButtons = false;
                              _this.doCloseRefuse();
                          });
                       }).catch(reason => {
                           _this.refuseFormLoading = false;
                           console.error(reason);
                       });
                    } else {
                        _this.refuseFormLoading = false;
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });
            },
            /**
             * 关闭拒绝表单
             * */
            doCloseRefuse(){
                this.refuseFormVisible = false;
                if(this.$refs['refuseForm']) this.$refs['refuseForm'].resetFields();
            },

            /**
             * 提交发送预准/发送特殊优惠
             * */
            doSubmitSpecial(){
                const _this = this;
                const _model = "PhysicalRoomSpecialOffer";
                const _actionName = "send_special_offer";
                let _formData = this.specialForm;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val && (val !== 0 || val !== '0')){
                        delete _formData[key];
                    }
                }
                const dateRange = _formData.dateRange;
                if(!dateRange || dateRange.length == 0){
                    _this.specialBtnDisabled = true;
                    _this.$message.error('Duplicate date selected!');
                    return;
                }

                const _firstDate = dateRange[0];
                const _lastDate = dateRange[1];
                const days = this.getDays(_firstDate,_lastDate);
                _formData.start_date = moment(_firstDate).format('YYYY-MM-DD');
                _formData.nights = days;
                delete _formData["dateRange"];

                this.$refs['specialForm'].validate((valid) => {
                    if (valid) {
                        _this.specialFormLoading = true;
                        if(_formData.id){
                            updateModel(_model, _formData.id, _formData).then(res => {
                                _this.specialFormLoading = false;
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });
                                _this._doAccept(_model,_actionName,_formData.id,()=>{
                                    _this.showButtons = false;
                                    _this.doCloseSpecial();
                                });
                            }).catch(reason => {
                                _this.specialFormLoading = false;
                                console.error(reason);
                            });
                        }else{
                            addModel(_model, _formData).then(res =>{
                                _this.specialFormLoading = false;
                                const _id = res.data.id;
                                _this.specialForm.id = _id;
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });
                                _this._doAccept(_model,_actionName, _id,()=>{
                                    _this.showButtons = false;
                                    _this.doCloseSpecial();
                                });
                            }).catch(reason => {
                                _this.specialFormLoading = false;
                                console.error(reason);
                            });
                        }

                    } else {
                        _this.specialFormLoading = false;
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });
            },
            doResetSpecial(){
                this.specialForm = {};
                if(this.$refs['specialForm']) this.$refs['specialForm'].resetFields();
            },
            /**
             * 关闭发送预准/发送特殊优惠表单
             * */
            doCloseSpecial(){
                this.specialFormVisible = false;
                this.specialForm = {};
                if(this.$refs['specialForm']) this.$refs['specialForm'].resetFields();
            },
            /**------- 2020.03.03 外包 CODE END ------**/
        },
        watch: {
            showModal() {
                if (!this.showModal) {
                    this.questionnaires = []
                    this.questionnaireIndex = 0;
                }
            },
            chatList() {
                if (this.chatList && this.chatList.chat_list) {
                    this.$nextTick(() => {
                        this.initChatListWrapper()
                    })
                }
            },
            msgList() {
                if (this.msgList && this.msgList.msg_list) {
                    this.$nextTick(() => {
                        this.initMessageWrapper()
                    })
                }
            },
            '$route'() {
                if (this.$route.name.indexOf('Chat') === -1) return

                if (this.$route.query.search) {
                    this.searchKeyword = this.$route.query.search
                    this.loadChat('all')
                } else {
                    this.loadChat('new')
                }

                clearInterval(this.interval)
                this.interval = window.setInterval(() => {
                    this.loadChat(this.type, false)
                }, 30000)
            },
            chatLang(val, oldVal) {
                if (this.chatLangFlag) {
                    updateModel('Chat', this.currentChat.chat_id, {
                        language_locked: true,
                        language: val
                    }).then(res => {
                        this.loadChat(this.type, true)
                    }).catch(e => {
                        this.loadChat(this.type, true)
                    })
                }
            },
            keyChatLang() {
                this.loadChat(this.type)
            }
        }
    }
</script>
<style lang="stylus">
    .input-size
       width:100%;

    .mail-chat
        padding-left: 10px;
        .translate-wrapper
            padding: 9.5px;
            margin: 10px 0 10px;
            font-size: 13px;
            line-height: 1.42857143;
            color: #333;
            word-break: break-all;
            word-wrap: break-word;
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 4px;
        .chat-left-aside
            .chat-left-header
                .text
                    font-size: 16px;
                padding: 15px;
                background-color: #337ab7;
                color: #fff;
                .chat-lang-wrapper
                    display: inline-block;
                    background-color #909090;
                    float: right;
                    border-radius: 4px;
                    .lang
                        float: left;
                        cursor: pointer;
                        &.active
                            background-color: #01c0c8;
        .chat-main-header
            .chat-lang-ctl
                .country-wrapper
                    display: block;
                    cursor: pointer;
                    border: 1px solid rgb(221, 221, 221);
                    img
                        width: 30px;
                        display: block;
                .dropdown-menu
                    min-width: 215px;
                    padding: 20px 0;
                .lang-ctl
                    display: inline-block;
                    margin: 0 5px;
        .slide-content
            margin: 0 !important;
            width: 100% !important;
        .box-title
            position: relative;
        .bookmark
            cursor: pointer;
            color: #FFD566;

        .language-wrapper
            height: 40px;
            line-height: 40px;
            .menu-select
                height: 40px;
                line-height: 40px;
            .lang-item
                padding: 4px 5px;
                font-size: 12px;
                cursor: pointer;
                border-radius: 4px;
                &.active
                    background-color: #2cabe3
                    color: #fff
        .hot-template
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 100px;
            display: inline-block;
            cursor: pointer;
        .chat-main-box .chat-right-aside .send-chat-box textarea.form-control
            height: 90px;
            padding-right: 0;
        #room div
            word-break: break-all;
        #order div
            word-break: break-all;
        .chat-main-box
            position: relative;
            overflow: visible;
            .chat-toggle-wrapper
                position: absolute;
                left: -24px;
                top: 35%;
                .chat-btn
                    border: 1px solid #dedede;
                    background-color: #fff;
                    text-align: center;
                    width: 24px;
                    padding: 10px 0;
                    cursor: pointer;
                    &.active
                        i
                            color: #ffa500;
                            font-weight: bold;
        .chat-main-box .chat-left-aside .chat-left-inner .style-none li
            overflow: visible;
        .chat-right-aside
            margin: 0 350px 0 300px
        .chat-aside
            position: absolute
            width: 350px
            right: 0
            top: 0
            border-left: 1px solid rgba(120, 130, 140, .13)
            bottom: 0
            .chat-aside-content
                padding: 10px;
                .pid-title
                    font-size: 20px;
                    color: orange;
                    margin: 0;
                .room-img
                    display: inline-block;
                    width: 100%;
                .room-title-wrapper
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    border-bottom: 1px solid #f2f3f4;
                    padding-right: 15px;
                    .room-title-left
                        flex: 1;
                        .room-title
                            font-size: 15px;
                            margin: 0;
                        .room-location
                            a
                                font-size: 12px;
                                color: #1c83bc;
                    .room-title-right
                        width: 40px;
                        img
                            border-radius: 50%;
                            width: 100%;
                .info-wrapper
                    border-bottom: 1px solid #f2f3f4;
                    padding-bottom: 10px;
                    .info-item
                        flex: 1;
                        .key
                            font-weight: bold;
                            font-size: 12px;
                            margin-bottom: 4px;
                        .val
                            font-size: 12px;
                        .check-time
                            margin-top: 4px;
                            font-size: 13px;
                    .info-top
                        display: flex;
                        align-items: center;
                        .btn-wrapper
                            display: flex;
                            align-items: center;
                    .info-bottom
                        margin-top: 20px;
                        display: flex;

        .chatonline
            .unseen
                font-weight: 600 !important
            li.active
                background-color: #3c8dbc;
                .name
                    color: #fff !important;
                .time
                    color: #fff !important;
                a:hover
                    background: #337ab7 !important;

    .small .full-calendar-body .dates .dates-events .events-week .events-day
        min-height: 50px !important;

    .small .full-calendar-body .dates .week-row .day-cell
        min-height: 50px !important;

    .small .full-calendar-body .dates .dates-events .events-week .events-day .event-box .event-item
        font-size: 12px;
        height: 12px;
        line-height: 12px;

    @media (max-width: 768px)
        .mail-chat
            .chat-left-aside
                position: static !important;
                width: 100%;
            .chat-right-aside
                margin: 0 !important;
            .chat-aside
                position: static !important;
                width: 100%

    .btn-wrapper
        .btn-circle
            width: 26px;
            height: 26px;
            padding: 6px 0;
            border-radius: 13px;
            text-align: center;
            font-size: 12px;
            line-height: 0.428571;
</style>
